import { FC, useEffect, useRef, useState } from "react"
import Taro, { useRouter } from '@tarojs/taro'
import uncheck from '../../../resource/uncheck.png'
import checked from '../../../resource/checked.png'
import { AtMessage } from 'taro-ui'
import style from './style.less'
import { Picker } from "@tarojs/components"

const WayBill: FC = () => {
  const router = useRouter()
  const param = useRef(JSON.parse(router.params.res as string))
  console.log('传过来的参数', param.current);

  const [check, setCheck] = useState(false)
  const [select, setSelect] = useState(0)
  const deposit = useRef<HTMLInputElement>(null)
  const freight = useRef<HTMLInputElement>(null)
  const loadingContactor = useRef<HTMLInputElement>(null)
  const unloadingContactor = useRef<HTMLInputElement>(null)
  const remark = useRef<HTMLTextAreaElement>(null)
  // const estimate = useRef<number>(0)
  const [estimate, setEstimate] = useState(0)
  const temperatureRange = ['-22°C以下', '-18°C以下', '-18-0°C', '0-10°C', '10-20°C', '20°C以上']
  const humidityRange = ['≦50%', '50-60%', '65-70%', '75-85%', '80-90%', '85-95%', '90-95%', '95-100%']
  const temperature = useRef<HTMLInputElement>(null)
  const humidity = useRef<HTMLInputElement>(null)

  // 防止重复发货
  const flag = useRef(false)

  useEffect(() => {
    Taro.showLoading({ title: '加载中' })
    Taro.request({
      url: 'http://10.190.84.29:9527/fta-cargo/publish/getPrePrice',
      method: 'POST',
      data: JSON.stringify({
        openId: Taro.getStorageSync('token'),
        cargoWeight: param.current.truckWeight,
        cargoCapacity: param.current.cargoCapacipy,
        secondCategory: param.current.cargoName,
        loadHhour: param.current.loadTime,
        truckType: param.current.truckType,
        truckLength: param.current.truckLength,
        startLon: param.current.loadLongitude,
        startLat: param.current.loadLatitude,
        endLon: param.current.unloadLongitude,
        endLat: param.current.unloadLatitude,
      }),
      success: (data) => {
        console.log('预估运费', data);
        loadingContactor.current!.value = data.data.phone
        unloadingContactor.current!.value = data.data.phone
        if (isNaN(data.data.price)) {
          freight.current!.value = '1437'
          setEstimate(1437)
          // estimate.current = 1437
        } else {
          freight.current!.value = String(data.data.price)
          setEstimate(data.data.price)
          // estimate.current = data.data.price
        }

        Taro.hideLoading()
        Taro.atMessage({
          message: `已为您预估此单运费供您参考，估价：${freight.current!.value}元`,
          type: 'success',
          duration: 300000
        })
      },
      fail: () => {
        console.log('预估运费失败');
        Taro.hideLoading()
      }
    })
  }, [])

  const showTip = () => {
    console.log('失去焦点时调用');
    if (estimate * 0.8 > Number(freight.current?.value)) {
      Taro.showModal({
        title: '提示',
        content: '您填写的一口价小于市场平均价格的80%，会对成交率有一定影响，是否继续？',
        success: function (res) {
          if (res.confirm) {
            console.log('用户点击确认')
          } else if (res.cancel) {
            console.log('用户点击取消')
            freight.current!.value = String(estimate)
          }
        }
      })
    }
  }

  const handleChange = (e, num) => {
    if (num === 1) {
      temperature.current!.value = temperatureRange[e.detail.value]
      param.current.temperature = e.detail.value
    } else {
      humidity.current!.value = humidityRange[e.detail.value]
      param.current.humidity = e.detail.value
    }
  }

  const submit = () => {
    if (!check) {
      Taro.showToast({
        title: '请勾选同意协议',
        icon: 'none',
        duration: 1500
      })
      return
    }

    if (flag.current) {
      return
    }

    flag.current = true

    if (param.current.truckType === '冷藏车' && (!temperature.current?.value || !humidity.current?.value)) {
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none',
        duration: 1500
      })
      return
    }

    if (deposit.current?.value && freight.current?.value &&
      loadingContactor.current?.value && unloadingContactor.current?.value
    ) {
      param.current.deposit = Number(deposit.current.value)
      param.current.cargoFee = Number(freight.current.value)
      param.current.loadLinkman = loadingContactor.current.value
      param.current.unloadingLinkman = unloadingContactor.current.value
      param.current.remark = remark.current?.value
      param.current.needReturnDeposit = select

      console.log(param.current);
      Taro.showLoading({ title: '发货处理中' })
      Taro.request({
        url: 'http://10.190.84.29:9527/fta-cargo/publish/publishCargo',
        method: 'POST',
        data: JSON.stringify({
          ...param.current
        }),
        success: (data) => {
          console.log('运单提交', data);

          if (data.data.data.result) {
            Taro.hideLoading()
            Taro.reLaunch({ url: '/packageA/success/index?title=发货结果&info=发货成功～' })
          } else {
            flag.current = false
            Taro.showToast({
              title: '发货失败',
              icon: 'none',
              duration: 1500
            })
          }
        },
        fail: () => {
          flag.current = false
          Taro.hideLoading()
        }
      })
    } else {
      flag.current = false
      Taro.showToast({
        title: '请填写完整信息',
        icon: 'none',
        duration: 1500
      })
    }
  }

  return (
    <div className={style.root}>
      <div className="money">
        <div className="title">订金</div>
        <input type="number" ref={deposit} placeholder="20-200元" value={50} />
        <div className={select === 0 ? "btn select" : "btn"} onClick={() => { setSelect(0) }}>不退还</div>
        <div className={select === 1 ? "btn select" : "btn"} onClick={() => { setSelect(1) }}>退还</div>
      </div>
      <div className="price">
        <div className="title">一口价</div>
        <input type="number" ref={freight} placeholder={`估价：${estimate}元`} onBlur={showTip} />
      </div>
      <div className="person">
        <div className="title">装货联系人</div>
        <input type="number" ref={loadingContactor} maxLength={11} placeholder="必填" />
      </div>
      <div className="person">
        <div className="title">卸货联系人</div>
        <input type="number" ref={unloadingContactor} maxLength={11} placeholder="必填" />
      </div>
      <div style={{ display: param.current.truckType === '冷藏车' ? 'block' : 'none' }}>
        <div className="person">
          <div className="title">温度范围</div>
          <Picker mode='selector' range={temperatureRange} onChange={(e) => { handleChange(e, 1) }}>
            <input type="number" ref={temperature} placeholder=">" disabled />
          </Picker>
        </div>
        <div className="person">
          <div className="title">湿度范围</div>
          <Picker mode='selector' range={humidityRange} onChange={(e) => { handleChange(e, 2) }}>
            <input type="number" ref={humidity} placeholder=">" disabled />
          </Picker>
        </div>
      </div>
      <div className="remarks">
        <div className="title">备注</div>
        <textarea ref={remark} placeholder="该项可不填" />
      </div>
      <div className="auto" onClick={() => { setCheck(!check) }}>
        {check ? <img src={checked} alt="" /> : <img src={uncheck} alt="" />}
        {' '}我已阅读并同意<i>《货物运输协议》</i>
      </div>
      <div className="submit" onClick={submit}>确认发货</div>
      <AtMessage />
    </div>
  )
}

export default WayBill